package com.gzhryc.shared_device.oem.code.profit.service;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import com.gzhryc.common.NumberTools;
import com.gzhryc.common.StringTools;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.jdbc.JdbcSession;
import com.gzhryc.jdbc.MultiDBTools;
import com.gzhryc.shared_device.base.models.OperateInfo;
import com.gzhryc.shared_device.oem.code.ConfigUtils;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentReferrerBusinessConfig;
import com.gzhryc.shared_device.oem.code.agent.services.AgentReferrerWalletService;
import com.gzhryc.shared_device.oem.code.config.BusinessConfig;
import com.gzhryc.shared_device.oem.code.profit.UserProfitConstants;
import com.gzhryc.shared_device.oem.code.profit.dao.AgentReferrerOrderProfitDao;
import com.gzhryc.shared_device.oem.code.profit.dao.db.AgentReferrerOrderProfit;
import com.gzhryc.shared_device.oem.code.profit.dao.db.BusinessOrderUserProfit;
import com.gzhryc.shared_device.oem.code.profit.dao.enums.BusinessOrderUserProfitEnum;
import com.gzhryc.shared_device.oem.code.profit.service.dto.BusinessOrderUserProfitSearch;
import com.gzhryc.shared_device.oem.code.user.ERoleType;
import com.gzhryc.shared_device.oem.code.user.dao.db.User;
import com.gzhryc.shared_device.oem.code.user.services.UserService;

public class AgentReferrerOrderProfitService {
	
	 static Logger log = Logger.getLogger(AgentReferrerOrderProfitService.class);

    public static AgentReferrerOrderProfitService self(Date date) {
        return MultiDBTools.getService(AgentReferrerOrderProfitService.class, date);
    }

    public static AgentReferrerOrderProfitService self(String jdbcKey,Date date) {
        return MultiDBTools.getService(jdbcKey, AgentReferrerOrderProfitService.class, date);
    }

    AgentReferrerOrderProfitDao dao;

    public AgentReferrerOrderProfitService(String jdbcKey,Date date) {
        dao = new AgentReferrerOrderProfitDao(jdbcKey,date);
    }
	
	public AgentReferrerOrderProfit getByTradeNo(String tradeNo) {
		if(StringTools.isNotBlank(tradeNo)) {
			try {
				return dao.getById(tradeNo);
			} catch (SQLException e) {
				log.error(e.getMessage(), e);
			}
		}
		return null;
	}
	
	public boolean saveToPay(AgentReferrerOrderProfit referrerOrderProfit,OperateInfo operateInfo) throws LogicException {
		JdbcSession.begin();
		try {
			if(dao.insert(referrerOrderProfit) > 0) {
				//修改账号钱包
				if(AgentReferrerWalletService.self().addMoney(referrerOrderProfit.getUserId(), referrerOrderProfit.getReferrerUserId(),
						referrerOrderProfit.getAccountGroupId(), referrerOrderProfit.getMoney(), operateInfo)) {
					JdbcSession.commit();
					return true;
				}else {
					log.error("增加代理介绍人账号钱包金额失败，{0:json}", referrerOrderProfit);
				}
			}
		} catch (SQLException e) {
			log.error(e.getMessage(), e);
		}finally {
			JdbcSession.end();
		}
		return false;
	}
	
	public boolean revokeIncome(AgentReferrerOrderProfit referrerOrderProfit,OperateInfo operateInfo) throws LogicException {
		JdbcSession.begin();
		try {
			if(dao.deleteById(referrerOrderProfit.getTradeNo()) > 0) {
				//修改账号钱包
				if(AgentReferrerWalletService.self().reduceMoney(referrerOrderProfit.getUserId(), referrerOrderProfit.getReferrerUserId(),
						referrerOrderProfit.getAccountGroupId(), referrerOrderProfit.getMoney(), operateInfo)) {
					JdbcSession.commit();
					return true;
				}else {
					log.error("减少代理介绍人账号钱包金额失败，{0:json}", referrerOrderProfit);
				}
			}
		} catch (SQLException e) {
			log.error(e.getMessage(), e);
		}finally {
			JdbcSession.end();
		}
		return false;
	}
	
	public void createToPay(AgentReferrerBusinessConfig agentReferrerBusiCfg,Date startDate,Date endDate
			,OperateInfo operateInfo) throws LogicException {
		if(agentReferrerBusiCfg != null && startDate != null && endDate != null) {
			//按支付组进行分成
			BusinessConfig busiCfg = ConfigUtils.getBusinessConfig();
			
			if(agentReferrerBusiCfg.getReferrerUser() == null) {
				User user = UserService.self().getById(agentReferrerBusiCfg.getReferrerUserId());
				if(user != null) {
					agentReferrerBusiCfg.setReferrerUser(user);
				}else {
					throw new LogicException("未找到介绍人信息");
				}
			}
	
			BusinessOrderUserProfitSearch search = new BusinessOrderUserProfitSearch();
			search.setAgentId(agentReferrerBusiCfg.getUserId());
			search.setBusinessType(agentReferrerBusiCfg.getBusinessType());
			search.setRoleType(ERoleType.Sys.index());
			search.setUserId(UserProfitConstants.PlatformServerUserId);
			search.setState(BusinessOrderUserProfitEnum.State.Finish.index());
			search.setStartCreateDate(startDate);
			search.setEndCreateDate(endDate);
	
			Integer pageNo = 1;
			Integer pageLimit = 100;
			List<BusinessOrderUserProfit> orderUserProfitList  = BusinessOrderUserProfitService.self(startDate)
					.findBySearch(search,pageNo,pageLimit);
			while(orderUserProfitList != null && orderUserProfitList.size() > 0) {
				for(BusinessOrderUserProfit orderUserProfit:orderUserProfitList) {
					if(orderUserProfit.getIncomeRatio() > busiCfg.getServiceChargeRatio()) {
						try {
							AgentReferrerOrderProfit profitRecord = getByTradeNo(orderUserProfit.getTradeNo());
							if(profitRecord == null) {
								//计算分成比例
								Double referrerIncomeRatio = orderUserProfit.getIncomeRatio() - busiCfg.getServiceChargeRatio();
								Double tempIncomeRatio = NumberTools.divide(referrerIncomeRatio, orderUserProfit.getIncomeRatio(),2);
								//分成金额
								Double money = NumberTools.multiply(NumberTools.changeMoneyLi(orderUserProfit.getMoney()),tempIncomeRatio);
								
								profitRecord = new AgentReferrerOrderProfit();
								profitRecord.setTradeNo(orderUserProfit.getTradeNo());
								profitRecord.setOrderDate(orderUserProfit.getOrderDate());
								profitRecord.setUserId(agentReferrerBusiCfg.getUserId());
								profitRecord.setReferrerUserId(agentReferrerBusiCfg.getReferrerUserId());
								profitRecord.setReferrerUserName(agentReferrerBusiCfg.getReferrerUser().getName());
								profitRecord.setReferrerUserPhone(agentReferrerBusiCfg.getReferrerUser().getPhone());
								profitRecord.setBusinessType(orderUserProfit.getBusinessType());
								profitRecord.setAccountGroupId(orderUserProfit.getAccountGroupId());
								profitRecord.setOrderProfitMoney(orderUserProfit.getMoney());
								profitRecord.setIncomeRatio(referrerIncomeRatio);
								profitRecord.setMoney(NumberTools.changeMoneyLi(money));
								profitRecord.setCreateDate(new Date());
								
								this.saveToPay(profitRecord, operateInfo);
							}
						}catch(Exception e) {
							log.error(e.getMessage(), e);
						}
					}
				}
				pageNo = pageNo + 1;
				orderUserProfitList  = BusinessOrderUserProfitService.self(endDate)
						.findBySearch(search,pageNo,pageLimit);
			}
		}
	}
}
